/// <reference path="../../typings/index.d.ts" />
'use strict';
const express = require('express');
const router = express.Router();
const mongoose = require('mongoose');
const UserInfo = mongoose.model('UserInfo');

module.exports = {
    userEixst: (req, res, next) => {
        UserInfo.find({ username: req.body.username }, (err, user) => {
            if (err) {
                return res.json({
                    err: err,
                    msg: '获取数据失败，请重新尝试！',
                    data: null
                })
            }
            if (user.length > 0) {
                return res.json({
                    err: null,
                    msg: '用户名已存在！',
                    data: user
                })
            }
            next();
        })
    },
    userRegister: (req, res, next) => {
        const { username, userpass } = req.body;
        let user = new UserInfo({ username, userpass });
        user.save(err => {
            if (err) {
                return res.json({
                    err: err,
                    msg: '注册失败',
                    data: null
                })
            } else {
                res.json({
                    err: null,
                    msg: '注册成功！！',
                    data: user
                })
            }
        })
    },
    findAll: (req, res, next) => {
        UserInfo.find((err, userinfos) => {
            if (err) {
                return res.json({
                    err: err,
                    msg: '查找时出现错误！！',
                    data: null
                })
            } else {
                return res.json({
                    err: null,
                    msg: '获取数据成功！',
                    data: userinfos
                })
            }
        })
    },
    findByStr: (req, res, next) => {
        UserInfo.find(req.findByStr, (err, userinfos) => {
            if (err) {
                return res.json({
                    err: err,
                    msg: '查找时出现错误！！',
                    data: null
                })
            } else {
                return res.json({
                    err: null,
                    msg: '获取数据成功！',
                    data: userinfos
                })
            }
        })
    },
}